'''
Function:
    运行game
author:
    walker
time:
    2020/5/14
'''
import sys
from config import *
from game import *
from game_parser import *
from cells import *
from player import *
from grid import *

'''给cells初始化'''
def init_cells(all_cells_lists):
    all_sprites_list = []

    for i in range(len(all_cells_lists)-1):
        list_item = []
        for j in range(len(all_cells_lists[i])):
            list_item.append(Cell(all_cells_lists[i][j]))
        all_sprites_list.append(list_item)

    return all_sprites_list

'''主函数'''
def main():
    load_level = Game_parse()
    #list中的str格式的地图（第一关）
    grid_list_str = load_level.read_txt(LEVEL1)
    #第二关
    # grid_list_str = load_level.read_txt(LEVEL2)
    #将上述地图转为list中包含list的格式
    grid_list_list,value_error_list = load_level.parse_str_to_list(grid_list_str)
    #检查地图是否存在错误
    load_level.value_error_input(value_error_list)
    # 获取到每个cell的坐标及其display
    all_cells_lists,all_cells_lists_pos = record_cells_info(grid_list_list)
    #初始化地图中所有的对象（水、火.....）
    all_sprites_list = init_cells(all_cells_lists)
    #初始化橡子
    acorn_sprites = Player(all_cells_lists[-1][0],0)
    #获取到水火所处位置的list
    water_lists = all_cells_lists_pos[4]
    fire_lists = all_cells_lists_pos[5]
    #输出第一步的地图，这一步是起始点被橡子所覆盖
    cover_start_to_A(grid_list_str,all_cells_lists[-1])

    #清屏代码
    # os.system("cls")
    #检测游戏是否能运行
    running = True
    while running:
        # 检测非法输入
        move = None
        try:
            move = input('Input a move:')
            if move not in INPUT_LIST:
                print("Please enter a valid move (w, a, s, d, e, q).")
            else:
                #橡子的初始位置
                acorn_sprites_ori_pos = [acorn_sprites.row,acorn_sprites.col]
                #检查是否可以移动
                acorn_sprites,is_exit,is_move = check_move(len(grid_list_str),len(grid_list_str[0]),acorn_sprites,move,all_cells_lists_pos[0])

                #如果到达终点，则胜利
                if acorn_sprites.row == all_cells_lists_pos[3][0][0] and acorn_sprites.col == all_cells_lists_pos[3][0][1]:
                    win_lose(acorn_sprites,'YOU WIN',WIN_INFO)
                    running = False
                    break
                #如果输入的是esc键，则直接退出游戏
                if is_exit == True:
                    win_lose(acorn_sprites,'YOU LOSE',LOST_INFO)
                    running = False
                    break

                grid_list_list,value_error_list = load_level.parse_str_to_list(grid_list_str)

                grid_process = Grid()
                grid_list_str,acorn_sprites.num_water_buckets = grid_process.grid_to_string(grid_list_list,acorn_sprites)
                if acorn_sprites.num_water_buckets < 0:
                    win_lose(acorn_sprites,'YOU LOSE',LOST_INFO)
                    running = False
                    break

                # 将返回的地图字符串按照\n来切片，并且截取[:-1]这一段当作地图
                grid_list_str = grid_list_str.split('\n')[:-1]

                #刷新入口
                if all_cells_lists_pos[2][0] != [acorn_sprites.row,acorn_sprites.col]:
                    grid_list_str_row = list(grid_list_str[all_cells_lists_pos[2][0][0]])
                    grid_list_str_row[all_cells_lists_pos[2][0][1]] = 'X'
                    grid_list_str_row = ''.join(grid_list_str_row)
                    grid_list_str[all_cells_lists_pos[2][0][0]] = grid_list_str_row

                #刷新传送门
                for trans_item in all_cells_lists_pos[6]:
                    index = all_cells_lists_pos[6].index(trans_item)
                    trans_num = all_cells_lists[6][index][2]
                    if trans_item != [acorn_sprites.row,acorn_sprites.col]:
                        # print("还没有到突然送到")
                        grid_list_str_row = list(grid_list_str[trans_item[0]])
                        grid_list_str_row[trans_item[1]] = trans_num
                        grid_list_str_row = ''.join(grid_list_str_row)
                        grid_list_str[trans_item[0]] = grid_list_str_row
                    else:
                        # print("到传送点了")
                        for grid_list_str_item in grid_list_str:
                            print(grid_list_str_item)
                        print("Whoosh! The magical gates break Physics as we know it and opens a wormhole through space and time.\n")
                        trans_flag = input("Press 'e' to start crossing or press 'w','a','s','d' to quit:  ")
                        if trans_flag == 'e':
                            acorn_sprites,grid_list_str = player_trans(acorn_sprites,grid_list_str,trans_num)

                #将运动后的地图画出
                for grid_list_str_item in grid_list_str:
                    print(grid_list_str_item)
                print("")
                print("You have %d water buckets."%acorn_sprites.num_water_buckets)

        except:
            raise ValueError("Sorry, an unknown error has occurred:)\n")


if __name__ == '__main__':
    main()
